package com;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SellTicket1 implements Runnable {//定义一个卖票类实现Runnable接口
    private int ticket=100;//定义票总数为100张
    private Lock lock = new ReentrantLock();//创建锁的对象
    @Override
    public void run() {//重写Runnable接口中Run方法
        while (true) {//使用while死循环进行卖票//
            try {//
                lock.lock();//
                if (ticket > 0) {//如果票数大于0//
                    try {//使用trycatch进行捕获异常//
                        Thread.sleep(100);//当三个线程拿到CPU执行权后等待0.1秒
                    } catch (InterruptedException e) {//
                        e.printStackTrace();//
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");//就在三个线程中卖出
                    //
                    ticket--;//
                }
            } finally {//
                lock.unlock();  //解锁
            }
        }
    }
}



